
package com.be.beadmin.quality.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.quality.dto.input.InspectionTemplateDto;
import com.be.beadmin.quality.dto.input.InspectionTotal;
import com.be.beadmin.quality.dto.output.InspectionTemplateEx;
import com.be.beadmin.quality.entity.InspectionTemplate;
import com.be.beadmin.quality.entity.InspectionTemplateMasterItem;
import com.be.beadmin.quality.entity.InspectionTemplate_;
import com.be.beadmin.quality.entity.TemplateInspectionItem;
import com.be.beadmin.quality.mapper.InspectionTemplateMapper;
import com.be.beadmin.quality.mapper.InspectionTemplateMapperEx;
import com.be.beadmin.quality.mapper.InspectionTemplateMasterItemMapper;
import com.be.beadmin.quality.mapper.TemplateInspectionItemMapper;
import com.be.beadmin.quality.repository.InspectionTemplateMasterItemRepository;
import com.be.beadmin.quality.repository.InspectionTemplateRepository;
import com.be.beadmin.quality.repository.TemplateInspectionItemRepository;
import com.be.beadmin.quality.service.InspectionTemplateService;
import com.be.beadmin.service.dto.output.DictDataEx;
import com.be.beadmin.service.entity.DictType;
import com.be.beadmin.service.repository.DictTypeRepository;
import com.be.beadmin.service.service.DictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @description 服务实现
* @author ljh
* @date 2023-05-18
**/
@Service
@RequiredArgsConstructor
public class InspectionTemplateServiceImpl implements InspectionTemplateService {

    @Autowired
    private  InspectionTemplateRepository inspectionTemplateRepository;
    @Autowired
    private  InspectionTemplateMapper inspectionTemplateMapper;
    @Autowired
    private  InspectionTemplateMapperEx inspectionTemplateExMapper;

    @Autowired
    private DictTypeRepository dictTypeRepository;

    @Autowired
    private DictDataService dictDataService;

    @Autowired
    private InspectionTemplateMasterItemRepository inspectionTemplateMasterItemRepository;

    @Autowired
    private TemplateInspectionItemRepository templateInspectionItemRepository;

    @Autowired
    private InspectionTemplateMasterItemMapper inspectionTemplateMasterItemMapper;

    @Autowired
    private TemplateInspectionItemMapper templateInspectionItemMapper;



    @Override
    public Page<InspectionTemplateEx> getInspectionTemplateByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<InspectionTemplate> page = inspectionTemplateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(InspectionTemplate_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(InspectionTemplate_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<InspectionTemplateEx> page1 = page.map(inspectionTemplateExMapper::toEntity);
            return page1;

    }

    @Override
    public void addInspectionTemplate(InspectionTemplateDto inspectionTemplateDto) {
            InspectionTemplate result = inspectionTemplateRepository.findInspectionTemplateByIdAndDelete(inspectionTemplateDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("InspectionTemplate不存在,请重新查询");
            }
            inspectionTemplateDto.setVision("1");
            InspectionTemplate inspectionTemplate = inspectionTemplateMapper.toEntity(inspectionTemplateDto);
            inspectionTemplateRepository.save(inspectionTemplate);


    }

    @Override
    public void updateInspectionTemplate(InspectionTemplateDto inspectionTemplateDto) {
            InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateById(inspectionTemplateDto.getId());
            String vision = inspectionTemplate.getVision();
            int nxt = Integer.parseInt(vision)+1;
            inspectionTemplateDto.setVision(String.valueOf(nxt));
            inspectionTemplate = inspectionTemplateMapper.toEntity(inspectionTemplateDto);
            inspectionTemplateRepository.save(inspectionTemplate);
    }


    @Override
    public void delInspectionTemplate(String id) {
        InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateById(id);
        inspectionTemplate.setDelete(1);

        List<InspectionTemplateMasterItem> inspectionTemplateMasterItemList = inspectionTemplateMasterItemRepository.findInspectionTemplateMasterItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);
        for(InspectionTemplateMasterItem inspectionTemplateMasterItem:inspectionTemplateMasterItemList){
            inspectionTemplateMasterItem.setDelete(1);
            inspectionTemplateMasterItemRepository.save(inspectionTemplateMasterItem);
        }

        List<TemplateInspectionItem> templateInspectionItemList =templateInspectionItemRepository.findTemplateInspectionItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);
        for(TemplateInspectionItem templateInspectionItem:templateInspectionItemList){
            templateInspectionItem.setDelete(1);
            templateInspectionItemRepository.save(templateInspectionItem);
        }

        inspectionTemplateRepository.save(inspectionTemplate);
    }

    @Override
    public void delInspectionTemplates (List<String> ids) { }

    @Override
    public List<String> getInspectionType() {
        DictType dictType = dictTypeRepository.findDictTypeByDictName("检验表类型");
        List<DictDataEx> inspectionType =  dictDataService.getDictDataExByDictTypeId(dictType);
        List<String> inspectionTypeList = new ArrayList<>();
        inspectionType.forEach(role-> inspectionTypeList.add(role.getKeyName()));
        return inspectionTypeList;
    }

    @Override
    public void publishInspectionTemplate(String inspectionTemplateId,Date publishTime) {
        InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateById(inspectionTemplateId);
        String state = inspectionTemplate.getState();
        if(state.equals("0")) state = "1";
        else state = "0";
        inspectionTemplate.setPublishTime(publishTime);
        inspectionTemplate.setState(state);
        inspectionTemplateRepository.save(inspectionTemplate);
    }

    @Override
    public InspectionTemplate getInspectionTemplateByNameAndProductType(String name, String productType) {
        InspectionTemplate inspectionTemplate=inspectionTemplateRepository.findInspectionTemplateByNameAndProductTypeAndDelete(name,productType,0);
        return inspectionTemplate;
    }

    @Override
    public InspectionTotal getInspectionTemplateByProductTypeAndType(String type, String productType) {
        if(type==null) throw new BeadminException("未指定模板类型");
        if(productType==null) throw new BeadminException("未指定柜体类型");
        InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateByProductTypeAndTypeAndDelete(productType,type,0);
        if(inspectionTemplate.getState().equals("0")) throw new BeadminException("模板未发布") ;
        List<InspectionTemplateMasterItem> inspectionTemplateMasterItemList=inspectionTemplateMasterItemRepository.findInspectionTemplateMasterItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);
        List<TemplateInspectionItem> templateInspectionItemList = templateInspectionItemRepository.findTemplateInspectionItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);

        InspectionTotal inspectionTotal =new InspectionTotal();
        inspectionTotal.setInspectionTemplateDto(inspectionTemplateMapper.toDto(inspectionTemplate));
        inspectionTotal.setInspectionTemplateMasterItemDtoList(inspectionTemplateMasterItemMapper.toDto(inspectionTemplateMasterItemList));
        inspectionTotal.setTemplateInspectionItemDtoList(templateInspectionItemMapper.toDto(templateInspectionItemList));
        return inspectionTotal;
    }

    @Override
    public InspectionTotal getInspectionTemplateByProductTypeAndTypeAndName(String type, String productType, String name) {
        if(type==null) throw new BeadminException("未指定模板类型");
        if(productType==null) throw new BeadminException("未指定柜体类型");
        if(name==null) throw new BeadminException("未指定模糊查询使用的检验表名称");

        InspectionTotal inspectionTotal = new InspectionTotal();

        InspectionTemplate inspectionTemplate = inspectionTemplateRepository.findInspectionTemplateByProductTypeAndTypeAndDeleteAndNameLike(productType,type,0,"%"+name+"%");
        if(inspectionTemplate==null || inspectionTemplate.getState().equals("0"))  return null;

        List<InspectionTemplateMasterItem> inspectionTemplateMasterItemList=inspectionTemplateMasterItemRepository.findInspectionTemplateMasterItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);
        List<TemplateInspectionItem> templateInspectionItemList = templateInspectionItemRepository.findTemplateInspectionItemByInspectionTemplateIdAndDelete(inspectionTemplate.getId(),0);


        inspectionTotal.setInspectionTemplateDto(inspectionTemplateMapper.toDto(inspectionTemplate));
        inspectionTotal.setInspectionTemplateMasterItemDtoList(inspectionTemplateMasterItemMapper.toDto(inspectionTemplateMasterItemList));
        inspectionTotal.setTemplateInspectionItemDtoList(templateInspectionItemMapper.toDto(templateInspectionItemList));
        return inspectionTotal;
    }

    /**
     * 根据id获取检验表模板
     *
     * @param inspectionTemplateId
     * @return
     */
    @Override
    public InspectionTemplate getInspectionTemplateById(String inspectionTemplateId) {
        return inspectionTemplateRepository.findInspectionTemplateByIdAndDelete(inspectionTemplateId,0);
    }

    @Override
    public InspectionTemplate checkInspectionTemplateByProductAndProcess(String productType, String processName) {
        return inspectionTemplateRepository.findInspectionTemplateByTypeAndProductTypeAndProcessNameAndDelete("过程检验",productType,processName,0);
    }

}